package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.User;
import dao.ajaxDao;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class ajaxServlet
 */
@WebServlet("/ajax")
public class ajaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ajaxServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/json");
		ajaxDao ajaxDao = new ajaxDao();
		String action = request.getParameter("action");
		if (action != null && action.equals("changePage")) {
			int page = Integer.parseInt(request.getParameter("page")) * 10 - 10;
			List<User> users = ajaxDao.findByPage(page);
			PrintWriter writer = response.getWriter();
			JSONArray json = JSONArray.fromObject(users);
			writer.print(json);
		} else if (action != null && action.equals("totalPage")) {
			int total = ajaxDao.findNum();
			int totalPage = (total % 10 == 0) ? total / 10 : total / 10 + 1;
			PrintWriter writer = response.getWriter();
			writer.print(totalPage);
		} else if (action != null && action.equals("searchPage")) {
			int page = Integer.parseInt(request.getParameter("page")) * 10 - 10;
			String username = request.getParameter("name");
			List<User> users=ajaxDao.findByName(page,username);
			PrintWriter writer=response.getWriter();
			JSONArray json=JSONArray.fromObject(users);
			writer.print(json);
		}else if(action!=null&&action.equals("totalSearch")) {
			String username=request.getParameter("name");
			int total =ajaxDao.findNumByName(username);
			int totalPage = (total % 10 == 0) ? total / 10 : total / 10 + 1;
			PrintWriter writer =response.getWriter();
			writer.print(totalPage);
		}
	}

}
